package top.tenebrous.yzl.im.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import top.tenebrous.yzl.im.ImChatProcessor;
import top.tenebrous.yzl.im.contants.CommonConstants;
import top.tenebrous.yzl.im.context.ImContext;
import top.tenebrous.yzl.im.entity.ImWebSocketProperties;
import top.tenebrous.yzl.im.enums.ChatType;
import top.tenebrous.yzl.im.enums.MessageType;
import top.tenebrous.yzl.im.factory.message.MessageFactory;
import top.tenebrous.yzl.im.message.MessageChatList;
import top.tenebrous.yzl.im.message.MessageNotice;
import top.tenebrous.yzl.im.model.ImClientChatInfoBean;
import top.tenebrous.yzl.im.model.ImClientFriendsBean;
import top.tenebrous.yzl.im.model.ImClientGroupBean;
import top.tenebrous.yzl.im.model.ImClientUserBean;
import top.tenebrous.yzl.im.observer.AbstractChatRecord;
import top.tenebrous.yzl.im.utils.DateUtils;
import top.tenebrous.yzl.im.utils.WebSocketUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * websocket连接时，权限认证，session处理，群组查询等
 *
 * @author yazhang6
 */
@Slf4j
@Component
public class WebSocketChatListMessageHandler implements MessageHandler<MessageNotice>, InitializingBean {

    @Resource
    private MessageFactory messageFactory;

    @Resource
    private ImWebSocketProperties webSocketProperties;

    @Resource
    private AbstractChatRecord<MessageNotice> chatRecord;

    @Resource
    private ImContext imContext;

    @Resource
    private ImChatProcessor imChatProcessor;

    @SneakyThrows
    @Override
    public void execute(WebSocketSession session, MessageNotice message) {
        log.info("{} 推送消息列表开始:接收人id:{}", CommonConstants.LOG_PREFIX, message.getTo());
        ImClientChatInfoBean chatInfoBean = new ImClientChatInfoBean();

        // 判断公聊还是私聊
        if (ChatType.PRIVATE_CHAT_TYPE.getCode().equals(message.getChatType())) {
            // 私聊
            // 2、根据接收者id(toId)查询接收者信息
            ImClientUserBean toUserInfo = imChatProcessor.takeAfterChatUserInfo(message.getTo());
            // 2、查询接收者（toId）为主的好友（fromId）信息
            ImClientFriendsBean friendsBean = imChatProcessor.takeChatFriendInfo(message.getTo(), message.getFrom());
            log.info("{} 推送消息列表==>好友信息:{}", CommonConstants.LOG_PREFIX, JSON.toJSONString(friendsBean));
            // 组装基本展示数据
            MessageChatList chatList = new MessageChatList();
            chatList.setChatId(friendsBean.getFriendId());      // fromId
            chatList.setChatType(ChatType.PRIVATE_CHAT_TYPE.getCode());
            chatList.setChatName(StringUtils.isBlank(friendsBean.getFriendNotes()) ? handlerGroupName(friendsBean.getFriendName()) : handlerGroupName(friendsBean.getFriendNotes()));
            chatList.setImageUrl(friendsBean.getImageUrl());
            chatList.setUniqueId(friendsBean.getUniqueId());
            chatList.setTopFlag(friendsBean.getTopFlag());
            // 组装聊天信息
            chatInfoBean.setFromId(message.getFrom());
            chatInfoBean.setFromUserName(StringUtils.isBlank(friendsBean.getFriendNotes()) ? friendsBean.getFriendName() : friendsBean.getFriendNotes());
            chatInfoBean.setToId(message.getTo());
            chatInfoBean.setToUserName(toUserInfo.getUserName());
            chatInfoBean.setLastMessage(HandlerContent(message.getContent()));
            chatInfoBean.setLastMessageDate(handlerDate(new Date()));
            chatInfoBean.setIsRead(0);
            chatInfoBean.setNotReadNum(1);
            chatList.setImClientChatInfo(chatInfoBean);
            log.info("{} 推送消息列表==>推送好友聊天列表消息{}", CommonConstants.LOG_PREFIX, JSON.toJSONString(chatList));
            WebSocketUtils.send(session, chatList.getType(), chatList);

        } else {
            // 公聊
            // 1、根据发送者id(fromId)查询发送者信息
            ImClientUserBean fromUserInfo = imChatProcessor.takeAfterChatUserInfo(message.getFrom());
            // 1、获取群组信息
            ImClientGroupBean groupBean = imChatProcessor.takeChatGroupInfo(message.getGroupId(), WebSocketUtils.getUserIdBySession(session));
            // 获取好友列表群组是否置顶
            ImClientFriendsBean friendsBean = imChatProcessor.takeChatFriendInfo(WebSocketUtils.getUserIdBySession(session), message.getGroupId());
            MessageChatList chatList = new MessageChatList();
            chatList.setChatId(groupBean.getGroupId());
            chatList.setChatType(ChatType.PUBLIC_CHAT_TYPE.getCode());
            chatList.setChatName(StringUtils.isBlank(groupBean.getGroupLabel()) ? handlerGroupName(groupBean.getGroupName()) : handlerGroupName(groupBean.getGroupLabel()));
            chatList.setImageUrl(groupBean.getImageUrl());
            chatList.setUniqueId(groupBean.getUniqueId());
            chatList.setImClientChatInfo(groupBean.getChatInfoBean());
            chatList.setTopFlag(friendsBean.getTopFlag());
            chatInfoBean.setFromId(message.getFrom());
            chatInfoBean.setFromUserName(fromUserInfo.getUserName());
            chatInfoBean.setToId(message.getGroupId());
            chatInfoBean.setToUserName(handlerGroupName(groupBean.getGroupName()));
            chatInfoBean.setLastMessage(HandlerContent(message.getContent()));
            chatInfoBean.setLastMessageDate(handlerDate(new Date()));
            chatInfoBean.setIsRead(0);
            chatInfoBean.setNotReadNum(1);
            chatList.setImClientChatInfo(chatInfoBean);
            WebSocketUtils.send(session, chatList.getType(), chatList);
        }
        log.info("{} 推送消息列表结束:接收人id:{}", CommonConstants.LOG_PREFIX, message.getTo());
    }

    private String handlerGroupName(String groupName) {
        return StrUtil.isNotBlank(groupName) && groupName.length() <= 6 ? groupName : groupName.substring(0, 6) + "...";
    }

    private String HandlerContent(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        if (content.length() >= 9) {
            return content.substring(0, 9) + "...";
        }
        return content;
    }

    @Override
    public String getType() {
        return MessageType.LIST.getCode();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        messageFactory.register(MessageType.LIST, this);
    }

    private String handlerDate(Date sendTime) {
        if (DateUtil.isSameDay(sendTime, new Date())) {
            return DateUtils.dateToString(sendTime, "HH:mm");
        }
        return DateUtils.dateToString(sendTime, DateUtils.DEFAULT_DATE_FORMAT);
    }
}
